<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>社区论坛</title>
  <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', sans-serif;
      background-color: #f4f4f9;
    }

    .forum-container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }

    .category-filter {
      margin-bottom: 20px;
    }

    .category-btn {
      background-color: #e2e8f0;
      color: #333;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      margin-right: 10px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .category-btn.active {
      background-color: #007BFF;
      color: white;
    }

    .post-list {
      list-style-type: none;
      padding: 0;
    }

    .post-item {
      background-color: white;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
      border-radius: 5px;
      padding: 20px;
      margin-bottom: 20px;
      transition: transform 0.3s ease;
      cursor: pointer;
    }

    .post-item:hover {
      transform: scale(1.02);
    }

    .post-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .post-meta {
      color: #666;
      font-size: 14px;
      margin-bottom: 10px;
    }

    .post-content {
      color: #333;
    }
  </style>
</head>

<body>
<div class="forum-container">
  <!-- 添加新建帖子按钮 -->
  <button id="newPostButton" class="category-btn" style="background-color: #28a745; color: white;">新建帖子</button>
  <div class="category-filter">
    <button class="category-btn active" data-category="all">全部</button>
    <button class="category-btn" data-category="技术交流">技术交流</button>
    <button class="category-btn" data-category="生活分享">生活分享</button>
    <button class="category-btn" data-category="my-follows">我的关注</button>
  </div>
  <ul class="post-list" id="postList">
    <!-- 帖子内容将通过JavaScript动态插入 -->
  </ul>
</div>

<script th:inline="none">
    // 从后端接口获取帖子数据
    let currentPage = 1; // 当前页码
    const pageSize = 10; // 每页显示的帖子数量
    let isLoading = false; // 是否正在加载数据

    function loadPosts(page) {
        if (isLoading) return;
        isLoading = true;
        fetch(`/api/posts?page=${page}&size=${pageSize}`)
          .then(response => response.json())
          .then(data => {
                const posts = data.posts;
                const postList = document.getElementById('postList');

                posts.forEach(post => {
                    const postItem = document.createElement('li');
                    postItem.classList.add('post-item');
                    postItem.dataset.postId = post.id;
                    // 添加删除按钮到帖子项
                    postItem.innerHTML = `
                        <h3 class="post-title">${post.title}</h3>
                        <p class="post-meta">作者: ${post.author} | 时间: ${post.timestamp}</p>
                        <p class="post-content">${post.content}</p>
                        <button class="delete-btn" style="background-color: #dc3545; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">删除</button>
                        <button class="edit-btn" style="background-color: #007BFF; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; margin-left: 5px;">修改</button>
                    `;
                    postItem.addEventListener('click', function (event) {
                        // 避免点击删除和修改按钮触发帖子详情跳转
                        if (!event.target.classList.contains('delete-btn') && !event.target.classList.contains('edit-btn')) {
                            const postId = post.id;
                            window.location.href = `/post/detail?id=${postId}`;
                        }
                    });

                    // 为删除按钮添加点击事件
                    const deleteButton = postItem.querySelector('.delete-btn');
                    deleteButton.addEventListener('click', function () {
                        const postId = post.id;
                        fetch(`/api/posts/${postId}`, {
                            method: 'DELETE',
                        })
                          .then(response => {
                                if (response.ok) {
                                    console.log('帖子删除成功');
                                    // 从DOM中移除该帖子项
                                    postItem.remove();
                                } else {
                                    console.error('帖子删除失败');
                                }
                            })
                          .catch(error => {
                                console.error('删除帖子时出错:', error);
                            });
                    });

                    // 为修改按钮添加点击事件
                    const editButton = postItem.querySelector('.edit-btn');
                    editButton.addEventListener('click', function () {
                        const postId = post.id;
                        // 创建修改对话框
                        const dialog = document.createElement('div');
                        dialog.style.position = 'fixed';
                        dialog.style.top = '50%';
                        dialog.style.left = '50%';
                        dialog.style.transform = 'translate(-50%, -50%)';
                        dialog.style.backgroundColor = 'white';
                        dialog.style.padding = '20px';
                        dialog.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.3)';
                        dialog.style.zIndex = '1000';

                        dialog.innerHTML = `
                            <h3>修改帖子</h3>
                            <input type="text" id="editPostTitle" value="${post.title}" style="width: 100%; margin-bottom: 10px;">
                            <textarea id="editPostContent" style="width: 100%; height: 150px; margin-bottom: 10px;">${post.content}</textarea>
                            <select id="editPostCategory" style="margin-bottom: 10px;">
                                <option value="技术交流" ${post.category === '技术交流' ? 'selected' : ''}>技术交流</option>
                                <option value="生活分享" ${post.category === '生活分享' ? 'selected' : ''}>生活分享</option>
                            </select>
                            <button id="submitEditPost">提交</button>
                            <button id="cancelEditPost">取消</button>
                        `;

                        document.body.appendChild(dialog);

                        // 提交修改按钮点击事件
                        document.getElementById('submitEditPost').addEventListener('click', function () {
                            const title = document.getElementById('editPostTitle').value;
                            const content = document.getElementById('editPostContent').value;
                            const category = document.getElementById('editPostCategory').value;

                            // 发送数据到后台
                            fetch(`/api/posts/${postId}`, {
                                method: 'PUT',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({
                                    title: title,
                                    content: content,
                                    category: category
                                }),
                            })
                              .then(response => {
                                    if (response.ok) {
                                        console.log('帖子修改成功');
                                        // 关闭对话框
                                        document.body.removeChild(dialog);
                                        // 重新加载帖子列表
                                        fetch('/api/posts')
                                          .then(response => response.json())
                                          .then(data => {
                                                displayPosts('all');
                                            });
                                    } else {
                                        console.error('帖子修改失败');
                                    }
                                })
                              .catch((error) => {
                                    console.error('Error:', error);
                                });
                        });

                        // 取消修改按钮点击事件
                        document.getElementById('cancelEditPost').addEventListener('click', function () {
                            document.body.removeChild(dialog);
                        });
                    });

                    postList.appendChild(postItem);
                });

                currentPage++;
                isLoading = false;
            })
          .catch(error => {
                console.error('获取帖子数据失败:', error);
                isLoading = false;
            });
    }

    // 初始加载帖子
    loadPosts(currentPage);

    // 监听滚动事件
    window.addEventListener('scroll', function () {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
            loadPosts(currentPage);
        }
    });

    const postList = document.getElementById('postList');
    const categoryButtons = document.querySelectorAll('.category-btn');

    function displayPosts(category) {
      postList.innerHTML = '';
      let filteredPosts = [];
      if (category === 'all') {
        filteredPosts = posts;
      } else if (category === 'my-follows') {
        filteredPosts = myFollowsPosts;
      } else {
        filteredPosts = posts.filter(post => post.category === category);
      }

      filteredPosts.forEach(post => {
        const postItem = document.createElement('li');
        postItem.classList.add('post-item');
        postItem.dataset.postId = post.id;
        // 添加删除按钮到帖子项
        postItem.innerHTML = `
          <h3 class="post-title">${post.title}</h3>
          <p class="post-meta">作者: ${post.author} | 时间: ${post.timestamp}</p>
          <p class="post-content">${post.content}</p>
          <button class="delete-btn" style="background-color: #dc3545; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">删除</button>
        `;
        postItem.addEventListener('click', function (event) {
          // 避免点击删除按钮触发帖子详情跳转
          if (!event.target.classList.contains('delete-btn')) {
            const postId = post.id;
            window.location.href = `/post/detail?id=${postId}`;
          }
        });

        // 为删除按钮添加点击事件
        const deleteButton = postItem.querySelector('.delete-btn');
        deleteButton.addEventListener('click', function () {
          const postId = post.id;
          fetch(`/api/posts/${postId}`, {
            method: 'DELETE',
          })
          .then(response => {
            if (response.ok) {
              console.log('帖子删除成功');
              // 从DOM中移除该帖子项
              postItem.remove();
            } else {
              console.error('帖子删除失败');
            }
          })
          .catch(error => {
            console.error('删除帖子时出错:', error);
          });
        });

        postList.appendChild(postItem);
      });
    }

    categoryButtons.forEach(button => {
      button.addEventListener('click', function () {
        categoryButtons.forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');
        const category = this.dataset.category;
        displayPosts(category);
      });
    });



// 新建帖子按钮点击事件
document.getElementById('newPostButton').addEventListener('click', function () {
  // 创建对话框
  const dialog = document.createElement('div');
  dialog.style.position = 'fixed';
  dialog.style.top = '50%';
  dialog.style.left = '50%';
  dialog.style.transform = 'translate(-50%, -50%)';
  dialog.style.backgroundColor = 'white';
  dialog.style.padding = '20px';
  dialog.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.3)';
  dialog.style.zIndex = '1000';

  dialog.innerHTML = `
    <h3>新建帖子</h3>
    <input type="text" id="newPostTitle" placeholder="标题" style="width: 100%; margin-bottom: 10px;">
    <textarea id="newPostContent" placeholder="内容" style="width: 100%; height: 150px; margin-bottom: 10px;"></textarea>
    <select id="newPostCategory" style="margin-bottom: 10px;">
      <option value="技术交流">技术交流</option>
      <option value="生活分享">生活分享</option>
    </select>
    <button id="submitPost">提交</button>
    <button id="cancelPost">取消</button>
  `;

  document.body.appendChild(dialog);

  // 提交按钮点击事件
  document.getElementById('submitPost').addEventListener('click', function () {
    const title = document.getElementById('newPostTitle').value;
    const content = document.getElementById('newPostContent').value;
    const category = document.getElementById('newPostCategory').value;

    // 发送数据到后台
    fetch('/api/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: title,
        content: content,
        category: category
      }),
    })
    .then(response => {
      if (response.ok) {
        console.log('帖子提交成功');
        // 关闭对话框
        document.body.removeChild(dialog);
        // 重新加载帖子列表
        fetch('/api/posts')
          .then(response => response.json())
          .then(data => {
            displayPosts('all');
          });
      } else {
        console.error('帖子提交失败');
      }
    })
    .catch((error) => {
      console.error('Error:', error);
    });
  });

  // 取消按钮点击事件
  document.getElementById('cancelPost').addEventListener('click', function () {
    document.body.removeChild(dialog);
  });
});
</script>
</body>

</html>